package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppUserThreadLocal;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.dto.EntryDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import com.heima.search.task.TaskAsync;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class IArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private TaskAsync taskAsync;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {

        if (StringUtils.isEmpty(dto.getEquipmentId())){
            List<ApArticleSearch> list = new ArrayList<>();
            return ResponseResult.okResult(list);
        }
        //查询索引
        QueryBuilder query = QueryBuilders.matchQuery("title",dto.getSearchWords());
        Pageable pageable = PageRequest.of(dto.getPage().intValue()-1,dto.getSize(), Sort.Direction.DESC,"publishTime");
        Page<ApArticleSearch> search = articleRepository.search(query, pageable);

        //异步保存关键字
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        User user = AppUserThreadLocal.get();
        if (user != null){
            entryDto.setUserId(user.getUserId());
        }
        taskAsync.saveSearchRecord(entryDto,dto.getSearchWords());
        //返回数据
        return ResponseResult.okResult(search.getContent());
    }
}
